package cn.edu.niit.studyspace.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.util.List;

import cn.edu.niit.studyspace.R;
import cn.edu.niit.studyspace.bean.Music;
import cn.edu.niit.studyspace.util.DateUtil;

public class MusicAdapter extends RecyclerView.Adapter<MusicAdapter.ViewHolder>
    implements View.OnClickListener {

  private Context context;
  private List<Music> items;
  private OnItemClick onItemClick;

  public MusicAdapter(Context context, List<Music> items, OnItemClick onItemClick) {
    this.context = context;
    this.items = items;
    this.onItemClick = onItemClick;
  }

  @NonNull
  @Override
  public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view =
        LayoutInflater.from(parent.getContext()).inflate(R.layout.item_music, parent, false);
    view.setOnClickListener(this);
    return new ViewHolder(view);
  }

  @Override
  public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
    Music music = items.get(position);
    Glide.with(context)
        .load(music.getPic_small())
        .apply(new RequestOptions().placeholder(R.drawable.ic_defalut))
        .into(viewHolder.header);

    viewHolder.itemView.setTag(position);
    viewHolder.albumName.setText(music.getAlbum_title());
    viewHolder.songName.setText(music.getTitle());
    viewHolder.num.setText(position + 1 + "");
    viewHolder.artistName.setText(music.getArtist_name());
    viewHolder.duration.setText(DateUtil.formatLongTime(music.getFile_duration()));
  }

  @Override
  public int getItemCount() {
    return items.size();
  }

  public void notifyData(List<Music> data) {
    this.items = data;
    notifyDataSetChanged();
  }

  @Override
  public void onClick(View v) {
      //接口实现
    onItemClick.onItemClick(v, (int) v.getTag());
  }

    /**
     *定义一个接口用于Item点击
     */
  public interface OnItemClick {
    void onItemClick(View view, int position);
  }

  static class ViewHolder extends RecyclerView.ViewHolder {
    TextView num;
    ImageView header;
    TextView artistName;
    TextView songName;
    TextView albumName;
    TextView duration;

    public ViewHolder(@NonNull View itemView) {
      super(itemView);
      num = itemView.findViewById(R.id.num);
      header = itemView.findViewById(R.id.iv_song_pic);
      artistName = itemView.findViewById(R.id.tv_song_author);
      songName = itemView.findViewById(R.id.tv_song_name);
      albumName = itemView.findViewById(R.id.tv_song_album);
      duration = itemView.findViewById(R.id.tv_duration);
    }
  }
}
